package epsi.mobile.helpers;

import java.io.BufferedReader;

import java.io.InputStreamReader;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONObject;

import epsi.mobile.business.WeatherProcess;
import epsi.mobile.constants.ConfigurationConstants;
import epsi.mobile.constants.JsonWeatherDataConstants;
import epsi.mobile.entities.Store;
import epsi.mobile.entities.Weather;
import epsi.mobile.views.StoreDetailsActivity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;

//Manage the weather when app is online
public class JsonWeatherUpdateHelper extends AsyncTask<Object, Void, Object>
{

    private String               JsonResultWeather = ""; // the json in string
                                                         // format

    private JSONObject           JsonWeather;            // The full array
    private JSONArray            WeatherJsonArray;       // The array for
                                                         // weather data
    private JSONObject           TempJsonArray;          // the array for
                                                         // temperature data
    private JSONObject           WindJsonArray;          // the array for wind
                                                         // data

    private BufferedReader       bufferReader;           // Buffer for read json
    private String               Buffer;                 // the buffer

    private URL                  WeatherUrl;             // The weather api url
    private Weather              Weather;                // The weather of the
                                                         // selected store

    private StoreDetailsActivity c;                      // The store details
                                                         // activity, for wait
                                                         // end of async task

    private WeatherProcess       weatherProcess;         // the weather manager
    private Store                toGetWeather;           // The store who want
                                                         // to get the store

    // init the helper
    public JsonWeatherUpdateHelper(Activity ctx, Store toGetWeather)
    {
        c = (StoreDetailsActivity) ctx; // get the details activity
        weatherProcess = new WeatherProcess(c);
        this.toGetWeather = toGetWeather;
    }

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
    }

    @Override
    protected Object doInBackground(Object... arg0)
    {
        try
        {
            if (NetworkHelper.isOnline(c.getApplicationContext())) // If we have access to network
            {
                Weather = getWeather(toGetWeather); // get the weather
                weatherProcess.removeWeather(); // remove old weather
                weatherProcess.insertWeather(Weather); // insert new data
            }

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

    protected void onPostExecute(Object o)
    {
        super.onPostExecute(o);
        c.setWeather();
    }

	
	

    // Get the weather
    private Weather getWeather(Store str)
    {
        try
        {
            JsonWeather = getWeatherData(toGetWeather.getXposition(), toGetWeather.getYposition()); // Get the weather json
            Weather = weatherParsing(toGetWeather.getStoreId(), JsonWeather); // Create the weather object with the json

            return Weather;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

    // get the weather json
    private JSONObject getWeatherData(double latitude, double longitude)
    {
        try
        {
            Weather = new Weather();
            WeatherUrl = new URL(ConfigurationConstants.JsonWeatherURL + "&lat=" + latitude + "&lon=" + longitude);
            bufferReader = new BufferedReader(new InputStreamReader(WeatherUrl.openStream()));

            while ((Buffer = bufferReader.readLine()) != null)
            {
                JsonResultWeather += Buffer;
            }

            return new JSONObject(JsonResultWeather);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

    // Parse the json and create the Weather object
    private Weather weatherParsing(String storeId, JSONObject Reader)
    {
        try
        {
            Weather ret = new Weather();

            WeatherJsonArray = Reader.getJSONArray(JsonWeatherDataConstants.WEATHER_ARRAY);
            TempJsonArray = Reader.getJSONObject(JsonWeatherDataConstants.TEMP_ARRAY);
            WindJsonArray = Reader.getJSONObject(JsonWeatherDataConstants.WIND_ARRAY);

            JsonWeather = WeatherJsonArray.getJSONObject(0);

            ret.setWeather(JsonWeather.getString(JsonWeatherDataConstants.WEATHER));
            ret.setIcon(JsonWeather.getString(JsonWeatherDataConstants.ICON));
            String date = new SimpleDateFormat("dd/MM/yyyy - k", Locale.FRANCE).format(new Date()) + "h" + new SimpleDateFormat("mm", Locale.FRANCE).format(new Date());
            ret.setLastUpdate(date);

            ret.setTemperature(TempJsonArray.getDouble(JsonWeatherDataConstants.TEMPERATURE));
            ret.setWindSpeed(WindJsonArray.getDouble(JsonWeatherDataConstants.WIND));

            ret.setStoreId(storeId);
            return ret;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

}
